package com.zhukaoguan.boot11.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhukaoguan.boot11.entity.Food;
import com.zhukaoguan.boot11.mapper.FoodMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.yaml.snakeyaml.events.Event;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/food/")
public class FoodController {
    @Autowired(required = false)
    FoodMapper foodMapper;
    @Value("${dirPath}")
    private String dirPath;
    @RequestMapping("show")
    public List<Food> select(){
        System.out.println("查食物图片");
        return foodMapper.select();
    }
    @RequestMapping("insert")
    public int add(Food food, MultipartFile picFile) throws IOException {
        String fileName =picFile.getOriginalFilename();
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        fileName= UUID.randomUUID()+suffix;
        File dirFile = new File(dirPath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath = dirPath+"/"+fileName;
        picFile.transferTo(new File(filePath));
        Food f = new Food();
       // f.setId(food.getId());
        f.setName(food.getName());
        f.setUrl("/"+fileName);
        f.setIntro(food.getIntro());
        f.setType(food.getType());
        System.out.println(f);
        return foodMapper.insert(f);
    }
    @RequestMapping("delete")
    public int delete(int id){
       return foodMapper.delete(id);
    }
    @RequestMapping("page")
    public PageInfo<Food> page(Integer pageNum){
        Integer pageSize=5;
        if (pageNum==null){
            pageNum=1;
        }
        PageHelper.startPage(pageNum,pageSize);
        List<Food> list =foodMapper.page(pageNum,pageSize);
        return new PageInfo<>(list);
    }
}
